<template>
  <van-nav-bar title="用户注册" left-arrow @click="goBack" />
  <van-row class="register-container">
    <van-col span="24">
      <van-form ref="formRef" required="auto">
        <van-field name="radio" label="性别" label-width="5rem" size="large" center>
          <template #input>
            <van-radio-group v-model="form.gender" checked-color="#667eea" direction="horizontal">
              <van-radio name="1">先生</van-radio>
              <van-radio name="0">女士</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field v-model="form.nickName" label-width="5rem" size="large"
          :rules="[{ required: true, message: '请输入昵称' }, { validator: validateNickName, message: '昵称需 2 - 16 位，仅包含中文、字母、数字和下划线' }]"
          label="昵称" placeholder="请输入昵称" maxlength="16" />
        <van-field v-model="form.phone" label-width="5rem" size="large"
          :rules="[{ required: true, message: '请输入手机号' }, { pattern: phonePattern, message: '请输入有效的手机号' }]" label="手机号"
          placeholder="请输入 11 位手机号" type="number" maxlength="11" />
        <van-field v-model="form.smsCode" label-width="5rem" size="large" center
          :rules="[{ required: true, message: '请输入短信验证码' }, { validator: validateSMSCode, message: '请输入 6 位数字验证码' }]"
          label="验证码" placeholder="请输入短信验证码" type="number" maxlength="6">
          <template #button>
            <van-button size="small" color="#667eea" :disabled="isSending || !isValidPhone" @click="sendSMSCode">
              {{ isSending ? `${countdown}s后重试` : '发送验证码' }}
            </van-button>
          </template>
        </van-field>
        <van-field v-model="form.password" label-width="5rem" size="large"
          :rules="[{ required: true, message: '请输入密码' }, { validator: validatePassword, message: '密码需 8 - 16 位，包含大小写字母、数字和特殊字符' }]"
          label="密码" placeholder="请输入密码" type="password" maxlength="16" />
        <van-field v-model="form.confirmPassword" label-width="5rem" size="large"
          :rules="[{ required: true, message: '请再次输入密码' }, { validator: validateConfirmPassword, message: '两次输入的密码不一致' }]"
          label="确认密码" placeholder="请再次输入密码" type="password" maxlength="16" />

        <van-button size="large" color="#667eea" block @click="handleRegister" style="margin-top: 30px;">
          注册
        </van-button>
      </van-form>
    </van-col>
  </van-row>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { smsCode, register } from '@/api/user';

const router = useRouter();

const isWechat = ref(false);
const form = ref({
  gender: '1',
  nickName: '',
  phone: '',
  smsCode: '',
  password: '',
  confirmPassword: '',
});
const isSending = ref(false);
const countdown = ref(60);
const phonePattern = /^1[3-9]\d{9}$/;
let timer = null;

const formRef = ref(null);

onMounted(() => {
  const userAgent = navigator.userAgent.toLowerCase();
  isWechat.value = userAgent.includes('micromessenger');
});

onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
});

const isValidPhone = computed(() => phonePattern.test(form.value.phone));

const validateNickName = (value) => {
  // 昵称需 2 - 16 位，仅包含中文、字母、数字和下划线
  return /^[\u4e00-\u9fa5a-zA-Z0-9_]{2,16}$/.test(value);
};

// 自定义短信验证码校验规则
const validateSMSCode = (value) => {
  return /^\d{6}$/.test(value);
};

// 自定义密码校验规则
const validatePassword = (value) => {
  // 密码需 8 - 16 位，包含大小写字母、数字和特殊字符
  return /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,16}$/.test(value);
};

// 自定义确认密码校验规则
const validateConfirmPassword = (value) => {
  return value === form.value.password;
};

const sendSMSCode = async () => {
  if (!isValidPhone.value) {
    showToast('请输入有效的手机号');
    return;
  }
  isSending.value = true;
  try {
    await smsCode('register', form.value.phone);
    timer = setInterval(() => {
      if (countdown.value > 0) {
        countdown.value--;
      } else {
        clearInterval(timer);
        isSending.value = false;
        countdown.value = 60;
      }
    }, 1000);
  } catch (error) {
    console.error('发送验证码失败:', error);
    isSending.value = false;
    showToast('发送验证码失败，请稍后重试');
  }
};

const handleRegister = async () => {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
    // console.log('注册信息：', form.value);
    register(form.value).then(res => {
      showDialog({
        message: '注册成功',
        confirmButtonColor: '#667eea',
      }).then(() => {
        router.push('/login');
      });
    });
  } catch (errors) {
    console.error('表单校验失败:', errors);
  }
};

const goBack = () => {
  router.push('/login');
};
</script>

<style scoped>
.register-container {
  padding: 15px;
  min-height: 100vh;
  overflow: hidden;
}
</style>
